package com.atguigu.lease.web.admin.service.impl;

import com.atguigu.lease.common.constant.RedisConstant;
import com.atguigu.lease.common.exception.LeaseException;
import com.atguigu.lease.common.result.ResultCodeEnum;
import com.atguigu.lease.common.utils.JwtUtil;
import com.atguigu.lease.model.entity.SystemUser;
import com.atguigu.lease.web.admin.mapper.SystemUserMapper;
import com.atguigu.lease.web.admin.service.LoginService;

import com.atguigu.lease.web.admin.vo.login.CaptchaVo;
import com.atguigu.lease.web.admin.vo.login.LoginVo;
import com.atguigu.lease.web.admin.vo.system.user.SystemUserInfoVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.wf.captcha.SpecCaptcha;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
public class LoginServiceImpl implements LoginService {

    @Autowired
    //private RedisTemplate redisTemplate;
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private SystemUserMapper systemUserMapper;

    /**
     * 获取图形验证码
     * @return
     */
    @Override
    public CaptchaVo getCheckCode() {

        //1.创建验证码对象
        SpecCaptcha specCaptcha = new SpecCaptcha(110, 51, 4);
        //2.获取验证码的文本内容
        String code = specCaptcha.text();
        //3.转换获取图片的地址
        String imageUrl = specCaptcha.toBase64();
        //4.生成key，唯一的
        String key = RedisConstant.ADMIN_LOGIN_PREFIX + UUID.randomUUID().toString().replaceAll("_", "");
        //5.存储Redis。并设置过期时间
        stringRedisTemplate.opsForValue().set(key,code,RedisConstant.ADMIN_LOGIN_CAPTCHA_TTL_SEC, TimeUnit.SECONDS);
        //6.返回验证码对象 key是redis中的key名。 因为一会要校验，前端将验证码的key回传，去redis查找，做对比
        CaptchaVo captchaVo = new CaptchaVo(imageUrl,key);
        return captchaVo;
    }

    /**
     * 登录校验
     * @param loginVo
     * @return
     */
    @Override
    public String login(LoginVo loginVo) {
        //1.获取前端发送的登录数据
        String username = loginVo.getUsername();
        String password = loginVo.getPassword(); //明文
        String captchaKey = loginVo.getCaptchaKey(); //redis中验证码的key
        String captchaCode = loginVo.getCaptchaCode(); //验证码里的字符串

        //2.判断验证码是否输入
        if (!StringUtils.hasText(captchaCode)){
            throw new LeaseException(ResultCodeEnum.ADMIN_CAPTCHA_CODE_NOT_FOUND);
        }

        //3.通过验证码的key从redis中获取验证码的value。若key不存在，则代表验证码过期了。
        String value = stringRedisTemplate.opsForValue().get(captchaKey);
        //3.1验证码过期校验
        if (value == null){
            //key没错 ，验证码过期了
            throw new LeaseException(ResultCodeEnum.APP_LOGIN_CODE_EXPIRED);
        }
        //3.2 验证码输入错误校验
       if (!captchaCode.equalsIgnoreCase(value)){
           throw new LeaseException(ResultCodeEnum.ADMIN_CAPTCHA_CODE_ERROR);
       }

       //验证码验证之后，要在redis中删除掉
        //stringRedisTemplate.delete(captchaKey);

        //4.根据用户名查询数据库
        SystemUser systemUser = systemUserMapper.selectOne(new LambdaQueryWrapper<SystemUser>()
                .eq(SystemUser::getUsername, username));
        if (systemUser == null){
            throw new LeaseException(ResultCodeEnum.ADMIN_ACCOUNT_NOT_EXIST_ERROR);
        }

        //5.判断是否被禁用 0
        if (systemUser.getStatus().getCode() == 0){
            throw new LeaseException(ResultCodeEnum.ADMIN_ACCOUNT_DISABLED_ERROR);
        }

        //6.判断密码，用前端的明文加密后，和数据库的密文做比较
       if (!DigestUtils.md5Hex(password).equals(systemUser.getPassword())){
           throw new LeaseException(ResultCodeEnum.ADMIN_ACCOUNT_ERROR);
       }

       //7.借助JWT工具类生成Token
        String token = JwtUtil.createToken(systemUser.getId(), systemUser.getUsername());
        return token;
    }

    /**
     * 获取登陆用户个人信息
     * @param userId
     * @return
     */
    @Override
    public SystemUserInfoVo getSystemctlUserInfoVOByUserId(Long userId) {
        SystemUser systemUser = systemUserMapper.selectById(userId);
        SystemUserInfoVo systemUserInfoVo = new SystemUserInfoVo();
        systemUserInfoVo.setName(systemUser.getName());
        systemUserInfoVo.setAvatarUrl(systemUser.getAvatarUrl());
        return systemUserInfoVo;
    }
}
